package com.yuexunit.websocket;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.util.HashMap;
import java.util.Map;

import org.apache.catalina.websocket.MessageInbound;
import org.apache.catalina.websocket.WsOutbound;

import com.yuexunit.finance.common.util.RandomUtil;
import com.yuexunit.util.StringUtil;

/**
*@version 创建时间：2016年12月2日 下午6:47:36
*@author wenwenlong
*类说明
*/

public class WebSocketMessageInbound extends MessageInbound{
	
	private String clientId;
	
	private String toClientId;
	
	private static final Map<String, MessageInbound> socketList = new HashMap<String, MessageInbound>();
	
	public WebSocketMessageInbound(String clientId, String toClientId) {
		if (StringUtil.isBlank(clientId)) {
			this.clientId = RandomUtil.generateTimeNumber();
		} else {
			this.clientId = clientId;
		}
	}
	
	//向单个客户端发送消息
	public static void send(String clientId, String message) throws IOException{
		MessageInbound messageInbound = socketList.get(clientId);
		messageInbound.getWsOutbound().writeTextMessage(CharBuffer.wrap(message));  
        messageInbound.getWsOutbound().flush(); 
	}
	
	//向所有客户端发送消息
	public static void send(String message) throws IOException{
		for (String clientId: socketList.keySet()) {
			MessageInbound messageInbound = socketList.get(clientId);
			messageInbound.getWsOutbound().writeTextMessage(CharBuffer.wrap(message));  
	        messageInbound.getWsOutbound().flush(); 
		}
	}

	@Override
	protected void onBinaryMessage(ByteBuffer message) throws IOException {
	}

	@Override
	protected void onTextMessage(CharBuffer message) throws IOException {
		String c = message.toString().split(",")[0];
		String m = message.toString().split(",")[1];
		send(c, m);
	}

	@Override
	protected void onOpen(WsOutbound outbound){
		try {
			socketList.put(clientId, this);
			MessageInbound messageInbound = this;
			messageInbound.getWsOutbound().writeTextMessage(CharBuffer.wrap(clientId));
			messageInbound.getWsOutbound().flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
	}

	@Override
	protected void onClose(int status) {
		socketList.remove(clientId);  
	}
}
